package org.deyang.tools.amazon;

import java.io.IOException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mortbay.log.Log;

import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

public class TwitterPostServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -1040939815366758544L;

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		Query twitterq = new Query("AmazonProduct");
		twitterq.addFilter("asin", Query.FilterOperator.EQUAL, req.getParameter("asin"));
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		PreparedQuery pq = datastore.prepare(twitterq);
		Entity resultEntity = pq.asSingleEntity();
		boolean postStatus = true;
		if (resultEntity != null){
			Twitter twitter = new TwitterFactory().getInstance();
		    try {
		    	String statusString = "" + resultEntity.getProperty("twitterSaleText") + resultEntity.getProperty("twitterProductDesc") + resultEntity.getProperty("twitterPostPrice") + " #amazon #deals " + resultEntity.getProperty("shorturl");
		    	StatusUpdate su = new StatusUpdate(statusString);
		    	
				Status status = twitter.updateStatus(su);
				resp.setStatus(200);
			} catch (TwitterException e) {
				Log.warn(e.getMessage());
				postStatus = false;
				resp.setStatus(400);
			}
		}else{
			resp.setStatus(403);
		}
		if (postStatus){
			resultEntity.setProperty("isPendingToTwitter", false);
			datastore.put(resultEntity);
		}
		try {
			Thread.sleep(30000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
